package com.jianganming.proxy.cglib;

import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;


public class ProxyPoint  implements MethodInterceptor {
    private TrainStation trainStation;
    public TrainStation getProxyObject(Class<? extends TrainStation> clazz)throws Exception{
        this.trainStation = clazz.newInstance();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return (TrainStation)enhancer.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
            throws Throwable {
        if("sellTickets".equals(methodProxy.getSignature().getName())){
            double price = (double) methodProxy.invokeSuper(o, objects);
            System.out.println("代售收取5%手续费,"+trainStation.getName()+"原价："+price);
            double price1 = price+(price * 0.05d);
            return price1;
        }else {
            return methodProxy.invokeSuper(o, objects);
        }

    }

    public static void main(String[] args)throws Exception {
        TrainStation proxyObject = new ProxyPoint().getProxyObject(GuangzhouTrainStation.class);
        double price = proxyObject.sellTickets();
        System.out.println(proxyObject.getName()+"现价:"+price);
        TrainStation proxyObject2 = new ProxyPoint().getProxyObject(ShanghaiTrainStation.class);
        double price2 = proxyObject2.sellTickets();
        System.out.println(proxyObject2.getName()+"现价:"+price2);

    }
}


interface TrainStation{
    //售票
    double sellTickets();
    //地名
    String getName();
}

//目标类
class GuangzhouTrainStation implements TrainStation {
    private double price;

    @Override
    public double sellTickets() {
        price = 200d;
        System.out.println("广州火车站卖票");
        return price;
    }

    @Override
    public String getName() {
        return "广州";
    }
}

//目标类
class ShanghaiTrainStation implements TrainStation {
    private double price;

    @Override
    public double sellTickets() {
        price = 150d;
        System.out.println("上海火车站卖票");
        return price;
    }

    @Override
    public String getName() {
        return "上海";
    }
}
